#include <iostream>
#include <string.h>

#include "file.h"

//constructor. Set file path.
File::File(std::string filePath):
    itsFilePath(filePath),
    itsFileBufferSS(std::stringstream::in |
                    std::stringstream::out |
                    std::stringstream::binary)
{}

//destructor. Make sure file is closed.
File::~File()
{
    //if file is open
    if(itsFile.is_open())
    {
        //close it..
        itsFile.close();
    }
}

//Read file contents to RAM.
bool File::ReadToRam()
{
    if(!Open())
        return false;

    itsFile.seekg(0, std::fstream::end);
    itsFileSize = itsFile.tellg();
    itsFile.seekg(0, std::fstream::beg);

    if(itsFileSize == 0)
        return false;

    char* tmp = new char[itsFileSize];
    itsFile.read(tmp, itsFileSize);
    itsFileBufferSS.write(tmp, itsFileSize-1);
    delete tmp;

    return true;
}

//Get address of itsFileBufferSS.
std::stringstream* File::GetPtrToFileBufferSS()
{
    return &itsFileBufferSS;
}

//private

//Open file.
bool File::Open()
{
    //Open file at itsFilePath for input.
    itsFile.open(itsFilePath.c_str(), std::fstream::in);

    //If it is not open return false
    if(!itsFile.is_open())
        return false;

    //Otherwise continue and return true
    return true;
}

//Close file.
void File::Close()
{
    //Check if file is open.
    if(itsFile.is_open())
    {
        //if it is open, close it.
        itsFile.close();

        //clear the file handle, just in case..
        itsFile.clear();
    }
}
